package b2.scene.fight
{
	import b2.config.*;
	import b2.net.*;
	import b2.player.*;
	import b2.scene.*;
	import b2.scene.camp.*;
	import b2.scene.guide.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.fight.*;
	import b2.widget.room.*;
	import b2.widget.task.*;
	
	import com.greensock.TweenLite;
	import com.smartfoxserver.v2.entities.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.text.*;
	
	import org.flixel.*;

	public class FightScene extends BasicScene
	{
		static private var instance:FightScene;
		public var leftPane:BattleLeftPane;
		public var rightPane:BattleRightPane;
		//当前战役索引
		private var _campIndex:int;
		//当前关卡 0, 1, 2, ...
		private var _battleOrder:int;
		private var battleGame:BattleGame;
		//特效层
		public var effectLayer:Sprite;
		//特效顶层
		public var effectTopLayer:Sprite; 
		//消息机制		
		public var eventDispatcher:EventDispatcher;
		
		//坦克在战役中得到的奖励（坦克id -> 物品列表（物品索引 -> 物品数量）） 
		public var awardList:Object;
		//顶部信息
//		private var topMessage:TextField;
		//底部消息
		private var bottomMessages:Array;
		//当前底部消息索引
		private var currentBottomMessage:int;
		//是否在游戏中
		private var inGameFlag:Boolean;

		public function FightScene()
		{
			super();
			//主游戏层
			battleGame = new BattleGame();
			addChild(battleGame);
			FlxG.mobile = true;
			//特效层
			effectLayer = new Sprite();
			addChild(effectLayer);
			//特效顶层
			effectTopLayer = new Sprite();
			addChild(effectTopLayer);
			//上方白条
			var bgr:Sprite = new Sprite();
			//上方白条缓存加速
			//bgr.cacheAsBitmap = true;
			var gfx:Graphics = bgr.graphics;
			gfx.moveTo(0, 0);
			gfx.beginFill(0xAAAAAA, 1);
			gfx.lineTo(BFont.stageWidth, 0);
			gfx.lineTo(BFont.stageWidth, 7.5);
			gfx.lineTo(0, 7.5);
			gfx.lineTo(0, 0);
			gfx.endFill();
			addChild(bgr);
			//下方白条
			bgr = new Sprite();
			//下方白条缓存加速
			//bgr.cacheAsBitmap = true;
			gfx = bgr.graphics;
			gfx.moveTo(0, 592.5);
			gfx.beginFill(0xAAAAAA, 1);
			gfx.lineTo(BFont.stageWidth, 592.5);
			gfx.lineTo(BFont.stageWidth, BFont.stageHeight);
			gfx.lineTo(0, BFont.stageHeight);
			gfx.lineTo(0, 592.5);
			gfx.endFill();
			addChild(bgr);
			//左侧面板
			leftPane = new BattleLeftPane();
			leftPane.x = 0;
			leftPane.y = 0;
			addChild(leftPane);
			//右侧面板
			rightPane = new BattleRightPane();
			rightPane.x = 692.5;
			rightPane.y = 0;
			addChild(rightPane);
			
			bottomMessages = new Array(5);
			
			//初始化消息器
			eventDispatcher = new EventDispatcher();
			
			eventDispatcher.addEventListener(FightEvent.TANK_KILLED, leftPane.onTankKilled);
			eventDispatcher.addEventListener(FightEvent.TANK_CREATED, rightPane.onTankCreated);
			eventDispatcher.addEventListener(FightEvent.TANK_LIFE_PLUS, leftPane.onTankLifePlus);
			eventDispatcher.addEventListener(FightEvent.TANK_STATUS_CHANGE, rightPane.onTankStatusChange);
			eventDispatcher.addEventListener(FightEvent.CLOCK_TICK, rightPane.onClockTick);
		}
		
		static public function getInstance():FightScene
		{
			if (!instance)
				instance = new FightScene();
			return instance;
		}
		
		public function generateMyAwardBalance():String
		{
			var objBalance:String = "";
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			var award:Object = this.awardList[me.campTankId];
			var count:int = 0;
			for (var comIndex:String in award)
			{
				var comIndexArr:Array = comIndex.split("_");
				var objectIndex:int = comIndexArr[0];
				var basicLevel:int = comIndexArr[1];
				var strengthenLevel:int = comIndexArr[2];
				if (count > 0)
					objBalance += ",";
				objBalance += PlayerInfoManager.getInstance().myUserId + "," + objectIndex + "," + basicLevel + "," + 
					strengthenLevel + ",0," + award[comIndex];
				count++;
			}
			return objBalance;
		}
		
		//获得玩家的房间位置
		public function getTankRoomPos(tankId:int):int
		{
			var playerSlot:PlayerSlot = leftPane.playerSlots[tankId];
			if (playerSlot != null)
			{
				return playerSlot.roomPos;
			}
			return -1;
		}
		
		//增加战利品
		public function addAwardList(tankId:int, objectIndex:int, basicLevel:int, strengthenLevel:int, objectNum:int, syncFlag:Boolean = false):void
		{
			if (tankId > 0)
			{
				var award:Object = this.awardList[tankId];
				var comIndex:String = objectIndex + "_" + basicLevel + "_" + strengthenLevel;
				if (award == null)
				{
					award = new Object();
					awardList[tankId] = award;
				}
				if (award[comIndex] == null)
					award[comIndex] = objectNum;
				else
					award[comIndex] += objectNum;
			}
			if (syncFlag)
			{
				SmartFoxHelper.getInstance().sendEchoRequest(SmartFoxHelper.AWARD_LIST_ADD, {"tankId": tankId, 
					"objectIndex": objectIndex, "basicLevel": basicLevel, "strengthenLevel": strengthenLevel, "objectNum": objectNum});
			}
		}
		
		//移除玩家
		public function removePlayer(playerName:String, tankId:int):void
		{
			if (inGameFlag)
			{
				leftPane.removePlaySlot(tankId);
				(FlxG.state as PlayState).killTank(tankId, -1);
				showBottomMessage("<font color='#0000FF'>" + playerName + "</font>离开了游戏。");
			}
		}
		
		//退出战役
		public function quit():void
		{
			inGameFlag = false;
			awardList = null;
			leftPane.clearPlayerSlot();
			FlxG.switchState(new FlxState());
			SceneManager.getInstance().loadScene(CampScene.getInstance());
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			var matchDialog:MatchDialog = WidgetManager.getInstance().getWidget(MatchDialog) as MatchDialog;
			//如果在比赛中 
			if (me.signUpMatchFlag && matchDialog != null) 
			{
				me.inMatchFlag = false;
				//进入签到房间
				SmartFoxHelper.getInstance().enterMatchSignUpRoom(matchDialog.campIndex, matchDialog.matchIndex);
			}
			else
			{
				SmartFoxHelper.getInstance().joinRoom(SmartFoxHelper.INITIAL_ROOM_NAME);
				var newFinishedTaskIndex:int = me.getNewFinishedTask();
				//如果有新完成的任务，弹出任务窗口
				if (newFinishedTaskIndex >= 0)
				{
					BottomBar.showTaskDialog();
					TaskDialog.getInstance().select(newFinishedTaskIndex);
				}
				GuideScene.getInstance().step++;
			}
		}
		
		//加载战役
		public function loadCamp(campIndex:int, isHeroMode:Boolean = false):void
		{
			if (!inGameFlag)
			{
				inGameFlag = true;
				_campIndex = campIndex;
				var campConfig:CampConfig = Config.campConfigs[campIndex];
				leftPane.campTopText.text = campConfig.name;
				//加载玩家
				leftPane.loadAllPlayerSlots(campIndex, isHeroMode);
				//重新初始化奖励
				awardList = new Object();
				_battleOrder = -1;
				startBattleByOrder(0, isHeroMode);
			}
		}
		
		//当前的战役
		public function get campIndex():int
		{
			return _campIndex;
		}
		
		//当前的关卡
		public function get battleOrder():int
		{
			return _battleOrder; 
		}
		
		//总关卡数
		public function get totalBattleNum():int
		{
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			return campConfig.battleIndex.length; 
		}
		
		//开始关卡（按战役中的位置）
		public function startBattleByOrder(bo:int, isHeroMode:Boolean = false):void
		{
			if (battleOrder != bo && bo < totalBattleNum)
			{
				_battleOrder = bo;
				var campConfig:CampConfig = Config.campConfigs[campIndex];
				leftPane.campBottomText.text = "第 " + (battleOrder + 1).toString() + " / " + totalBattleNum + " 关";
				TweenLite.delayedCall(0.5, startBattleByIndex, [parseInt(campConfig.battleIndex[battleOrder]), isHeroMode]);
			}
		}
		
		//开始关卡（按唯一号）
		private function startBattleByIndex(battleIndex:int, isHeroMode:Boolean):void
		{
			var fight:FightScene = FightScene.getInstance();
			var battleConfig:BattleConfig = Config.battleConfigs[battleIndex];
			fight.leftPane.goalBottomText.text = Config.basicConfig.goalName[battleConfig.goal];
			fight.rightPane.refresh();
			var playState:PlayState = new PlayState(battleIndex);
			playState.isHeroMode = isHeroMode;
			FlxG.switchState(playState);
		}
		
		//显示顶部信息
		public function showTopMessage(message:String):void
		{
			var topMessage:TextField = new TextField();
			topMessage.selectable = false;
        	topMessage.autoSize = TextFieldAutoSize.LEFT;
			topMessage.defaultTextFormat = new TextFormat("微软雅黑", 30, 0x000000, true);
			topMessage.filters = [new GlowFilter(0xFFFFFF, 1, 1.5, 1.5, 100, BitmapFilterQuality.HIGH)];
			topMessage.htmlText = message;
			topMessage.x = 400 - topMessage.width / 2;
			topMessage.y = 80;
			TweenLite.from(topMessage, 1, {y: 0, alpha:0});
			TweenLite.delayedCall(8, removeTopMessage, [topMessage]);
			addChild(topMessage);
		}
		
		private function removeTopMessage(topMessage:TextField):void
		{
			if (topMessage.parent != null)
			{
				topMessage.parent.removeChild(topMessage);
			}
		}
		
		//显示底部信息
		public function showBottomMessage(message:String, syncFlag:Boolean = false):void
		{
			var i:int = 0;
			while (i < bottomMessages.length && bottomMessages[i] != null)
			{
				if (bottomMessages[i].text == message)
					return;
				i++;
			}
			if (i < bottomMessages.length)
				currentBottomMessage = i;
			else
				currentBottomMessage = (currentBottomMessage + 1) % bottomMessages.length;
			removeBottomMessage(bottomMessages[currentBottomMessage]);
			var messageText:TextField = new TextField();
			messageText.selectable = false;
        	messageText.autoSize = TextFieldAutoSize.LEFT;
			messageText.defaultTextFormat = new TextFormat("微软雅黑", 14, 0x000000);
			messageText.filters = [new GlowFilter(0xFFFFFF, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			messageText.htmlText = message;
			messageText.x = 140;
			messageText.y = 565 - currentBottomMessage * 18;
			TweenLite.from(messageText, 1, {y: 750, alpha:0});
			bottomMessages[currentBottomMessage] = messageText;
			addChild(messageText);
			TweenLite.delayedCall(8, removeBottomMessage, [messageText]);
			if (syncFlag)
			{
				SmartFoxHelper.getInstance().sendEchoRequest(SmartFoxHelper.MESSAGE_SHOW, {"message": message});
			}
		}
		
		//移除底部信息
		private function removeBottomMessage(messageText:TextField):void
		{
			if (messageText == null)
				return;
			delete bottomMessages[bottomMessages.indexOf(messageText)];
			if (messageText.parent != null)
			{
				messageText.parent.removeChild(messageText);
			}
		}
		
		public override function destroy():void
		{
			super.destroy();
		}
		
		public function showEndPane(campIndex:int, battleOrder:int, winSide:int, evaluation:int):void
		{
			//如果已经显示了一个结束面板
			if (WidgetManager.getInstance().getWidget(BattleEndPane) != null)
				return;
			GuideScene.getInstance().clearLastStep();
			var state:PlayState = FlxG.state as PlayState;
			var fightScene:FightScene = SceneManager.getInstance().currentScene as FightScene;
			var campConfig:CampConfig = Config.campConfigs[fightScene.campIndex];
			if (fightScene.battleOrder >= campConfig.battleIndex.length - 1)
			{
				state.addedStatusAward();
				if (!SmartFoxHelper.getInstance().isSinglePlayer)
				{
					state.addedCooperationAward();
				}
			}
			var endPane:BattleEndPane = new BattleEndPane(campIndex, battleOrder, winSide, evaluation);
			endPane.x = (BFont.stageWidth - endPane.width) / 2;
			endPane.y = (BFont.stageHeight - endPane.height) / 2;
			TweenLite.from(endPane, 1, {y:-endPane.height});
			WidgetManager.getInstance().popOut([endPane]);
		}
	}
}